import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class HttpPage extends StatefulWidget {
  HttpPage({Key? key}) : super(key: key);

  @override
  _HttpPageState createState() => _HttpPageState();
}

class _HttpPageState extends State<HttpPage> {
  String _msg = '';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Http网络请求"),
      ),
      body: Column(
        children: [
          Text(_msg),
          SizedBox(
            height: 100,
          ),
          ElevatedButton(
            onPressed: () {
              _getHttp();
            },
            child: Text("GET"),
          ),
          SizedBox(
            height: 20,
          ),
          ElevatedButton(
            onPressed: () {
              _postHttp();
            },
            child: Text("Post"),
          ),
          ElevatedButton(
            onPressed: () {
              // _postHttp();
              Navigator.pushNamed(context, '/get');
            },
            child: Text("获取数据，渲染数据"),
          ),
        ],
      ),
    );
  }

  void _getHttp() async {
    var url = Uri.parse("https://jd.itying.com/api/httpGet");
    var reponse = await http.get(url);
    String a = reponse.body;
    var b = json.decode(a);
    print(reponse.statusCode);
    print(reponse.body);
    print(b["msg"]);
    setState(() {
      this._msg = b["msg"];
    });
  }

  void _postHttp() async {
    var url = Uri.parse("https://jd.itying.com/api/httpPost");
    var reponse = await http.post(
      url,
      body: {"username": "张三", "age": "20"},
    );
    String a = reponse.body;
    var b = json.decode(a);
    print(reponse.statusCode);
    print(reponse.body);
    print(b["msg"]);
    setState(() {
      this._msg = b["msg"];
    });
  }
}
